from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel
from typing import Optional

c03 = APIRouter()

"""
OAuth2 密码模式 和 FastAPI的OAuthPasswordBearer
当请求到来是， FastAPI会检查请求的Authorization头信息， 如果找不到、或者没有bearer token 返回 400
"""

oauth2_schema = OAuth2PasswordBearer(tokenUrl="/c03/token")


@c03.get("/oauth2_password_bearer")
async def oauth2_password_bearer(token: str = Depends(oauth2_schema)):
    return {"token": token}


"""基于Password 和 Bearer token 的OAuth2 认证"""

fake_user_db = {
    "john snow": {
        "username": "john snow",
        "full_name": "john snow",
        "email": "johnsnow@16.com",
        "hashed_password": "fakehashedfake",
        "disabled": False
    },
    "alice": {
        "username": "alice",
        "full_name": "alice",
        "email": "alice@16.com",
        "hashed_password": "fakehashedalice",
        "disabled": True
    }
}


def fake_hash_password(password: str):
    return "fakehashed" + password


class User(BaseModel):
    username: str
    email: Optional[str] = None
    full_name: Optional[str] = None
    disabled: Optional[bool] = None


class UserInDB(User):
    hashed_password: str


def get_user(db, username: str):
    if username in db:
        user_dict = db[username]
        return UserInDB(**user_dict)


def fake_decode_token(token: str):
    user = get_user(fake_user_db, token)
    return user


async def get_current_user(token: str = Depends(oauth2_schema)):
    user = fake_decode_token(token)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
            headers={"WWW-Authenticate": "Bearer"}
        )
    return user


async def get_current_active_user(current_user: User = Depends(get_current_user)):
    if current_user.disabled:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail="Inactive user"
        )
    return current_user


@c03.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    user_dict = fake_user_db.get(form_data.username)
    if not user_dict:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Incorrect username"
        )
    user = UserInDB(**user_dict)
    hashed_password = fake_hash_password(form_data.password)
    if not hashed_password == user.hashed_password:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Incorrect password")
    return {"access_token": user.username, "token_type": "Bearer"}


@c03.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_active_user)):
    return current_user
